package com.example.demo.web.filter;

import com.alibaba.fastjson.JSON;
import com.example.demo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Order(1)
public class LoginValidateFilter implements WebFilter {

    Logger log = LoggerFactory.getLogger(LoginValidateFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        Long start = System.currentTimeMillis();

        String token = exchange.getRequest().getHeaders().getFirst("token");

        if(!StringUtils.hasLength(token)){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            exchange.getResponse().getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8");
            //响应错误结果
            Result result = new Result(401,"无效的Token");
            byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Mono.just(dataBuffer));
        }

        return chain.filter(exchange).then(Mono.fromRunnable(()->{
            log.info("执行耗时 = {}",System.currentTimeMillis() - start);
        }));
    }
}
